const fs = require('fs');
function print(data) {
    if (!data) return;
    let str = JSON.stringify(data);
    Editor.log(str)
    console.log(data)
}

Editor.Panel.extend({
    style: `
      :host { margin: 5px; }
      h2 { color: #f90; }
      #content {
          width:80%;
          height:200;
          background:#ffffff;
          margin:15px;
          text-align:left;
          color:#ff0000;
      }
      #format {
          width:80%;
          height:200;
          background:#ffffff;
          margin:5px;
          text-align:left;
          color:#ff0000;
      }
    `,

    template: `
      <div id="root" style="width:100%; height:100%">
      <h2 style="text-align:center">ASSETLIST</h2>
      <ui-button id="loadData">读取数据</ui-button>
      <hr/>
      <ui-button id="addAttr">添加属性</ui-button>
      <ui-input id="addAttrWin" value="123"></ui-input>

      <ui-box-container id="attrWrap" folded="false">
        
      </ui-box-container>
      </div>
    `,



    $: {
        root: '#root',
        loadData: '#loadData',
        addAttr: '#addAttr',
        addAttrWin: '#addAttrWin',
        attrWrap: '#attrWrap',
    },

    body: null,


    ready() {
        Editor.log('ddd1', this.$root.style.width)
        Editor.log('ddd2', this.$root.clientWidth)
        this.body = document.getElementsByTagName('body')[0];

        window.onresize = () => {
            this.$loadData.style.width = "30%";
            this.$addAttr.style.width = "30%";
            this.$addAttrWin.style.width = "40%";
        }
        window.onresize()
        Editor.log('this.$loadData', this.$loadData.parentNode.children[0])
        Editor.log('this.$loadData', this.$loadData.parentNode.children[1])
        Editor.log('this.$loadData', this.$loadData.parentNode.children)
        Editor.log('this.$loadData', this.$loadData.parentNode.children[2].clientWidth)

        // Editor.Ipc.sendToMain('build_worker:loadAssetListData', (err, info) => {
        //     if (err) console.error(err);
        //     if (info) {
        //         Editor.log('data:', JSON.stringify(info));
        //         this.assetlistData = info;
        //         this.refreshAttrWin(info)
        //     }
        // }, 5000);

        // this.$addAttr.style.display = 'none';
        this.loadData();

        this.$loadData.addEventListener('confirm', () => {
            this.loadData();
        });
        this.$addAttr.addEventListener('confirm', () => {
            this.addAttr()
        });
    },
    whenReady() {
        console.log('whenReady')
    },
    // 复制数据按钮
    loadData() {
        Editor.log('loadData');
        for (let i of this.$attrWrap.children) {
            this.$attrWrap.removeChild(i);
        }

        // Editor.Ipc.sendToMain('build_worker:loadAssetListData', (err, info) => {
        //     if (err) console.error(err);
        //     if (info) {
        //         Editor.log('data:', JSON.stringify(info));
        //         this.assetlistData = info;
        //         this.refreshAttrWin(info)
        //     }
        // }, 5000);

        let data = loadAssetListData();
        Editor.log('data:', JSON.stringify(data));
        this.assetlistData = data;
        this.refreshAttrWin(data)
    },
    refreshAttrWin(object, lastWin) {
        // Editor.log('refreshAttrWin')
        lastWin = lastWin || this.$attrWrap;
        let curWin = document.createElement('ui-box-container');
        lastWin.appendChild(curWin);
        if (object instanceof Array) {
            if (object && object.length) {
                for (let i = 0; i < object.length; i++) {
                    let val = object[i];
                    if (typeof val != 'object') {
                        let e = document.createElement('ui-prop')
                        e.type = typeof val;
                        e.value = val;
                        curWin.appendChild(e);
                        e.addEventListener('confirm', () => {
                            this.changeData(object, e.name, e.value);
                        });
                    } else {
                        this.refreshAttrWin(val, curWin);
                    }
                }
            } else {
                lastWin.removeChild(curWin);
            }
        } else {
            let keys = Object.getOwnPropertyNames(object)
            // Editor.log('keys', keys)
            if (keys && keys.length) {
                for (let i = 0; i < keys.length; i++) {
                    let key = keys[i];
                    let val = object[key];
                    // Editor.log('val', val)
                    if (typeof val != 'object') {
                        let e = document.createElement('ui-prop')
                        e.name = key;
                        e.type = typeof val;
                        e.value = val;
                        curWin.appendChild(e);
                        e.addEventListener('confirm', () => {
                            this.changeData(object, e.name, e.value);
                        });
                    } else {
                        this.refreshAttrWin(val, curWin);
                    }
                }
            }
        }
    },

    changeData(object, name, value) {
        // Editor.log('changeData', object, name, value)
        object[name] = value;
        // Editor.log('this.assetlistData', this.assetlistData)
        // let res = this.assetlistHandler.saveAssetListData(this.assetlistData);
        // Editor.log('保存结果', res)
        saveAssetListData(this.assetlistData)

        // Editor.Ipc.sendToMain('build_worker:saveAssetListData', this.assetlistData, (e, res) => {
        //     Editor.log('保存结果', res)
        // });
    },

    addAttr() {
        Editor.log('addAttr');
    },

});
function flushData() {

}

function loadAssetListData(is_object = true) {
    let ccc_path = 'db://assets/assetlist.txt';
    let proj_path = Editor.url(ccc_path);
    let dataObject;
    // if (fs.existsSync(proj_path)) {

    Editor.log('proj_path', proj_path);
    let data = fs.readFileSync(proj_path);
    // Editor.log('data', !!data);
    try {
        if (data) {
            let dataStr = data.toString();
            // Editor.log('dataStr', dataStr); 
            if (is_object) {
                dataObject = eval(dataStr);
            } else {
                dataObject = dataStr;
            }
        }
        Editor.log('dataObject', dataObject);
    } catch (e) {
        Editor.error('数据格式错误', data)
    }
    // }
    return dataObject;
}
function saveAssetListData(data) {
    let ccc_path = 'db://assets/assetlist.txt';
    let proj_path = Editor.url(ccc_path);
    const fs = require('fs');
    // Editor.log('data', data);
    if (data) {
        let res = JSON.stringify(data);
        res = res.replace(/,/g, '\,\r\n\t');
        res = res.replace(/{/g, '\{\r\n\t');
        res = res.replace(/}/g, '\r\n\}');
        res = `(${res})`;
        // Editor.assetdb.createOrSave(ccc_path, res);
        // Editor.log('res', typeof res, res);
        fs.writeFile(proj_path, res, (e) => {
            if (e)
                Editor.error(e)
            else
                Editor.log('写入完成')
        });
    }
}